<template>
  <section>
    <section class="filter-bar mb-16">
      <span class="label">流水时间：</span>
      <a-range-picker style="width:320px;" allow-clear :placeholder="['起始时间', '终止时间']" show-time :value="time"
                      @change="getTime">
      </a-range-picker>
      <span class="ml-10 label">关联订单号：</span>
      <a-input
        class="w-160"
        v-model="orderId"
        :max-length="35"
        placeholder="请输入关联订单号"
        @pressEnter="search()"
        allow-clear/>
      <span class="ml-10 label">流水类型：</span>
      <a-select
        class="mr-24 w-140"
        allow-clear
        placeholder="选择流水类型"
        v-model="type"
        @change="search"
      >
        <a-select-option v-for="(item,i) in waterTypeList" :value="item.value" :key="i">
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-button type="primary" @click="search">查询</a-button>
      <a-button class="ml-8" @click="reset">重置</a-button>
    </section>
    <section class="filter-bar mb-16">
      <section>
        <a-button v-if="$permissionJudge('VendorBillAdd')" type="primary" icon="plus"
                  @click="createWater()">添加非结算流水
        </a-button>
        <a-button class="ml-8" v-if="$permissionJudge('OrderSettle')" type="primary" @click="$refs.settlement.open()">
          结算
        </a-button>
      </section>
    </section>
    <a-table
      class="table-con"
      row-key="id"
      :loading="loading"
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
    >
      <template #orderId="val">
        <a-tooltip :title="val">
          <span class="overflow" style="display:block;max-width:140px;">{{ val }}</span>
        </a-tooltip>
      </template>
      <template #remark="val">
        <a-tooltip :title="val">
          <span class="overflow" style="display:block;max-width:240px;">{{ val }}</span>
        </a-tooltip>
      </template>
    </a-table>
    <a-modal
      :maskClosable="false"
      :title="'新增账户流水信息'"
      :width="650"
      :visible="showModal"
      :confirm-loading="confirmLoading"
      :ok-type="'primary'"
      @ok="confirmOk"
      @cancel="cancel"
    >
      <a-form :form="form">
        <a-row :gutter="[24,0]">
          <a-col :span="12">
            <a-form-item class="mb-15" label="余额" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                class="w-full"
                placeholder="请输入余额(元)，正数"
                v-decorator="[
							'balanceAmount',
							{rules: [{validator:amountValidator}]}
						]"
                maxLength="15"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item style="margin-left: -5px;" class="mb-15" label="质量金" :label-col="labelCol"
                         :wrapper-col="wrapperCol">
              <a-input
                class="w-full"
                placeholder="请输入质量金，正数"
                v-decorator="[
							'creditAmount',
							{rules: [{validator:amountValidator}]}
						]"
                :min="0"
                maxLength="18"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="[24,0]">
          <a-col :span="12">
            <a-form-item class="mb-15" label="流水类型" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select
                placeholder="请选择流水类型"
                v-decorator="[
							'type',
							{rules: [{required: true, message: '请选择流水类型'}]}
						]">
                <a-select-option v-for="(item,i) in waterTypeList" :value="item.value" :key="i">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item style="margin-left: -5px;" class="mb-15" label="关联订单号" :label-col="labelCol"
                         :wrapper-col="wrapperCol">
              <a-input
                class="w-full"
                placeholder="请输入订单号"
                v-decorator="[
							'orderId',
							{rules: [{validator:orderValidator}]}
						]"
                :min="0"
                maxLength="18"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="[24,0]">
          <a-col :span="24">
            <a-form-item style="margin-left: -5px;" class="mb-15" label="流水备注" :label-col="{span: 4}"
                         :wrapper-col="{span: 20}">
              <a-textarea
                placeholder="请输入流水备注"
                v-decorator="[
							'remark',
							{rules: [{required: true,whitespace: true,message: '请输入流水备注'}]}
						]"
                :auto-size="{ minRows: 3, maxRows: 5 }"
                maxLength="300"
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <Settlement :vendor-id="id" ref="settlement" @success="getData"/>
  </section>
</template>
<script>
import {tableMixins} from '@/utils/mixins'
import {getPageVendorBillList, addVendorBill} from '@/api/vendor'
import Settlement from '@/views/order/order-settlement/Settlement'

export default {
  name: 'supplierWaterlist',
  mixins: [tableMixins],
  components: {Settlement},
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      labelCol: {span: 8},
      wrapperCol: {span: 16},
      showModal: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      loading: false,
      customerName: undefined,
      pageNum: 1,
      rowsNum: 10,
      columns: [
        {dataIndex: 'id', title: '流水号', align: 'center'},
        {dataIndex: 'createTime', title: '流水时间', align: 'center'},
        {dataIndex: 'amount', title: '金额(元)', align: 'center'},
        {dataIndex: 'orderId', align: 'center', title: '关联订单号', scopedSlots: {customRender: 'orderId'}},
        {dataIndex: 'typeDesc', align: 'center', title: '流水类型'},
        {dataIndex: 'remark', align: 'center', title: '备注', scopedSlots: {customRender: 'remark'}, width: 260}
      ],
      data: [],
      waterTypeList: [],
      time: undefined,
      times: undefined,
      orderId: undefined,
      type: undefined
    }
  },
  created() {
    this.getData()
    //流水类型数据字段
    this.$utils.getDictList('VendorBillTypeEnum').then(res => {
      this.waterTypeList = res
    })
  },
  methods: {
    orderValidator(rule, value, callback) {
      const amount = value && value.trim()
      const isAmount = /^([1-9]\d*|[0]{1,1})$/
      if (amount === '') {
        callback()
      }
      if (amount && !isAmount.test(amount)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    },
    amountValidator(rule, value, callback) {
      const amount = value && value.trim()
      const isAmount = /^(\+)?\d+(\.\d{1,2})?$/
      if (amount === '') {
        callback()
      }
      if (amount * 1 === 0 || amount && !isAmount.test(amount)) {
        callback(new Error('请输入正数且保留两位小数'))
      } else {
        callback()
      }
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const {id} = this
          const {balanceAmount, creditAmount} = values
          if (!balanceAmount && !creditAmount) return this.$message.warning('请填写金额或质量金！')
          addVendorBill({
            vendorId: id, ...this.$utils.trimValue(values),
            creditAmount: creditAmount ? creditAmount : undefined,
            balanceAmount: balanceAmount ? balanceAmount : undefined,
          }).then(() => {
            this.$message.success('新建成功！')
            this.$emit('upload')
            this.getData()
            this.cancel()
          })
        }
      })
    },
    //新建流水
    createWater() {
      this.showModal = true
    },
    getTime(e, stringTime) {
      this.time = e
      this.times = stringTime
    },
    search() {
      this.pageNum = 1
      this.getData()
    },
    reset() {
      this.time = undefined
      this.times = undefined
      this.orderId = undefined
      this.type = undefined
      this.search()
    },
    getData() {
      this.loading = true
      const {rowsNum, pageNum, id, times, orderId, type} = this
      getPageVendorBillList({
        vendorId: id,
        startTime: times ? times[0] : undefined,
        endDateTime: times ? times[1] : undefined,
        orderId: orderId ? orderId : undefined,
        rowsNum, pageNum,
        type
      }).then(res => {
        const {items, rowCount} = res
        this.data = items
        this.total = rowCount
      }).finally(() => {
        this.loading = false
      })
    },
    cancel() {
      this.confirmLoading = false
      this.form.resetFields()
      this.showModal = false
    }
  }
}
</script>
<style lang="less" scoped>
.table-con {
  /deep/ .ant-table-thead > tr > th, /deep/ .ant-table-tbody > tr > td {
    padding: 8px;
  }
}
</style>
